﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using DevExpress.Web.ASPxEditors;
using DevExpress.XtraPrinting;

namespace Project_Udrinkwater.Empoyee_Management
{
    public partial class OrderList : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            Session["Order_ID"] = Session["sOrder_ID"];
            if (!IsPostBack)
            {
                ShowdataHead();
            }
            
           
        }

        protected void ASPxGridView2_BeforePerformDataSelect(object sender, EventArgs e)
        {
            Session["Order_ID"] = Session["sOrder_ID"];
        }
        private void ShowdataHead()
        {
            DataTable dt = new DataTable();
            DataTable ds = new DataTable();
            DataTable df = new DataTable();
            //SELECT Order_ID, Order_doc_NO, Order_Date_Time, Credit, Deadlines_Date, Employee_ID, Customer_ID FROM TB_Order
            DataView dvSql = (DataView)SqlOrder.Select(DataSourceSelectArguments.Empty);
            dt = dvSql.ToTable();
            txtDocNo.Text = dt.Rows[0]["Order_doc_NO"].ToString();
            txtdocDate.Text = dt.Rows[0]["Order_Date_Time"].ToString();
            
            txtDeadline.Text = dt.Rows[0]["Deadlines_Date"].ToString();
            Session["sEmp_ID"] = dt.Rows[0]["Employee_ID"].ToString();
            Session["sCustomer_ID"] = dt.Rows[0]["Customer_ID"].ToString();
            
            
            DataView dvSql2 = (DataView)SqlEmp.Select(DataSourceSelectArguments.Empty);
            ds = dvSql2.ToTable();
            cmbEmp.Value = ds.Rows[0]["Employee_ID"].ToString();
           
            DataView dvSql3 = (DataView)SqlCustomer.Select(DataSourceSelectArguments.Empty);
            df = dvSql3.ToTable();
            string SS = Session["sCustomer_ID"].ToString();
            string ddd =  df.Rows[0]["Customer_ID"].ToString(); 
            cmbCustomer.Value = df.Rows[0]["Customer_ID"].ToString();
            txtAddress.Text = df.Rows[0]["Adress"].ToString() + "ตำบล " + df.Rows[0]["DISTRICT_NAME"].ToString() +
                              " อำเภอ " + df.Rows[0]["AMPHUR_NAME"].ToString() + "จังหวัด" +df.Rows[0]["PROVINCE_NAME"].ToString() + "" +
                              df.Rows[0]["Postcode"].ToString() +" \n"+ "โทรศัพท์ : " + df.Rows[0]["Phone"].ToString() +
                              " แฟกส์ : " + df.Rows[0]["Fax"].ToString();
        }
        protected void cmbProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            ASPxComboBox combo1 = (ASPxComboBox)sender;
            object oldCat1 = Session["sProduct_ID"];
            if (oldCat1 != null && oldCat1.Equals(combo1.Value)) return;
            Session["sProduct_ID"] = combo1.Value;
            //ASPxComboBox combo2 = ((ASPxComboBox) DetailGrid.FindEditRowCellTemplateControl(
            //    DetailGrid.Columns["Order_Category_ID"] as GridViewDataComboBoxColumn, "cmbOrdercate"));
            ASPxComboBox combo2 = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbOrdercate"));
            combo2.Value = null;

            cmbOrdercate_SelectedIndexChanged(combo2, EventArgs.Empty);
        }

        protected void cmbOrdercate_SelectedIndexChanged(object sender, EventArgs e)
        {
            ASPxComboBox combo2 = (ASPxComboBox)sender;
            object oldCat2 = Session["sOrderCatID"];
            if (oldCat2 != null && oldCat2.Equals(combo2.Value)) return;
            Session["sOrderCatID"] = combo2.Value;
            //ASPxComboBox combo3 = ((ASPxComboBox)DetailGrid.FindEditRowCellTemplateControl(
            //    DetailGrid.Columns["Price_Unit"] as GridViewDataComboBoxColumn, "cmbPrice"));
            ASPxComboBox combo3 = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbPrice"));
            combo3.Value = null;

        }
        protected string GetAmount()
        {
            ASPxTextBox Amount = grid.FindEditFormTemplateControl("txtAmount") as ASPxTextBox;
            return Amount.Text;
        }
        protected string GetDiscount()
        {
            ASPxTextBox Discount = grid.FindEditFormTemplateControl("txtDiscount") as ASPxTextBox;
            return Discount.Text;
        }
        
       
        protected void SqlOrder_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            e.Command.Parameters["@Order_ID"].Value = Session["sOrder_ID"].ToString();
        }

        protected void SqlEmp_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            e.Command.Parameters["@Employee_ID"].Value = Session["sEmp_ID"].ToString();
        }

        protected void SqlCustomer_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            e.Command.Parameters["@Customer_ID"].Value = Session["sCustomer_ID"].ToString();
        }

        protected void btnPdfExport_Click(object sender, EventArgs e)
        {
            DataTable df =new DataTable();
            DataView dvSql3 = (DataView)SqlCustomer.Select(DataSourceSelectArguments.Empty);
            df = dvSql3.ToTable();
            string SS = Session["sCustomer_ID"].ToString();
            string ddd =  df.Rows[0]["Customer_ID"].ToString(); 
            cmbCustomer.Value = df.Rows[0]["Customer_ID"].ToString();
            Session["Address"] = txtAddress.Text;
            //Session["Distric"] = df.Rows[0]["DISTRICT_NAME"].ToString();
            //Session["Amphur"] = df.Rows[0]["AMPHUR_NAME"].ToString();
            //Session["Province"] = df.Rows[0]["PROVINCE_NAME"].ToString();
            //Session["Postcode"] = df.Rows[0]["Postcode"].ToString();
            //Session["Phone"] = df.Rows[0]["Phone"].ToString();
            //Session["Fax"] = df.Rows[0]["Fax"].ToString();

            Session["DocDate"] = txtdocDate.Text;
            Session["DocNo"] = txtDocNo.Text;
            Session["DeeadLine"] = txtDeadline.Text;
            Session["Employee"] = cmbEmp.SelectedItem;
            Session["Customer"] = cmbCustomer.SelectedItem;
            SqlOrder.UpdateCommand = "UPDATE TB_Order SET DesAddres = '" + txtAddress.Text + "' WHERE (Order_ID = " + Session["Order_ID"].ToString() +")";
            SqlOrder.Update();
            Response.Redirect("OrderBill.aspx");
            
            //gridExport.ReportHeader = "\t\t\tใบเสร็จรับเงิน\n" +
            //                          "\tเลขที่เอกสาร : " + txtDocNo.Text + "\tวันที่เอกสาร :" + txtdocDate.Text+
            //                          "\tวันกำหนดส่ง :" + txtDeadline.Text +"\tชื่อพนักงาน: "+cmbEmp.Items +
            //                          "\tชื่อลูกค้า : " + cmbCustomer.Items;

            //using (MemoryStream ms = new MemoryStream())
            //{
            //    PrintableComponentLink pcl = new PrintableComponentLink(new PrintingSystem());
            //    pcl.Component = gridExport;
            //    pcl.CreateMarginalHeaderArea += new CreateAreaEventHandler(pcl_CreateMarginalHeaderArea);
            //    pcl.CreateMarginalFooterArea += new CreateAreaEventHandler(pcl_CreateMarginalFooterArea);
            //    pcl.Margins.Left = pcl.Margins.Right = 50;
            //    pcl.Landscape = false;
            //    pcl.CreateDocument(true);
            //    pcl.PrintingSystem.Document.AutoFitToPagesWidth = 1;
            //    pcl.ExportToPdf(ms);
            //    WriteResponse(Response, ms.ToArray(), System.Net.Mime.DispositionTypeNames.Attachment.ToString());
            //}
        }
        void pcl_CreateMarginalFooterArea(object sender, CreateAreaEventArgs e)
        {
            e.Graph.DrawBrick(new TextBrick() { Rect = new System.Drawing.RectangleF(0, 0, 0, 0), Text = "Test2" });

        }
        void pcl_CreateMarginalHeaderArea(object sender, CreateAreaEventArgs e)
        {
            e.Graph.DrawBrick(new TextBrick() { Rect = new System.Drawing.RectangleF(0, 0, 0, 0), Text = "Test" });
        }
       
        public static void WriteResponse(HttpResponse response, byte[] filearray, string type)
        {
            response.ClearContent();
            response.Buffer = true;
            response.Cache.SetCacheability(HttpCacheability.Private);
            response.ContentType = "application/pdf";
            ContentDisposition contentDisposition = new ContentDisposition();
            contentDisposition.FileName = "test.pdf";
            contentDisposition.DispositionType = type;
            response.AddHeader("Content-Disposition", contentDisposition.ToString());
            response.BinaryWrite(filearray);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            try
            {
                response.End();
            }
            catch (System.Threading.ThreadAbortException)
            {
            }

        }
        protected void btnXlsExport_Click(object sender, EventArgs e)
        {
            gridExport.WriteXlsToResponse();
        }
        protected void btnXlsxExport_Click(object sender, EventArgs e)
        {
            gridExport.WriteXlsxToResponse();
        }
        protected void btnRtfExport_Click(object sender, EventArgs e)
        {
            gridExport.WriteRtfToResponse();
        }
        protected void btnCsvExport_Click(object sender, EventArgs e)
        {
            gridExport.WriteCsvToResponse();
        }

        protected void grid_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {

            e.NewValues["Product_ID"] = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbProduct")).Value;
            e.NewValues["Order_Category_ID"] = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbOrdercate")).Value;
            e.NewValues["Price_Unit"] = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbPrice")).Value;
            e.NewValues["Amount"] = ((ASPxTextBox)grid.FindEditFormTemplateControl("txtAmount")).Text;
            e.NewValues["Discount"] = ((ASPxTextBox)grid.FindEditFormTemplateControl("txtDiscount")).Text;
        }

        protected void grid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {

            string aa = e.OldValues["Discount"].ToString();

            e.NewValues["Product_ID"] = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbProduct")).Value;
            e.NewValues["Order_Category_ID"] = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbOrdercate")).Value;
            e.NewValues["Price_Unit"] = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbPrice")).Value;
            e.NewValues["Amount"] = ((ASPxTextBox)grid.FindEditFormTemplateControl("txtAmount")).Text;
            e.NewValues["Discount"] = ((ASPxTextBox)grid.FindEditFormTemplateControl("txtDiscount")).Text;
        }

        protected void grid_HtmlEditFormCreated(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditFormEventArgs e)
        {
            ASPxComboBox combo2 = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbProduct") as ASPxComboBox);
            if (Request.Params[combo2.UniqueID] != null) return;
            if (!grid.IsNewRowEditing)
            {
                object[] vals = (object[])grid.GetRowValues(grid.EditingRowVisibleIndex,
                                                                   new string[]
                                                                       {
                                                                           "Product_ID", "Order_Category_ID",
                                                                           "Price_Unit","Amount","Discount"
                                                                       });

                ASPxComboBox combo3 = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbOrdercate") as ASPxComboBox);
                ASPxComboBox combo4 = ((ASPxComboBox)grid.FindEditFormTemplateControl("cmbPrice") as ASPxComboBox);
                ASPxTextBox txt1 = ((ASPxTextBox)grid.FindEditFormTemplateControl("txtAmount")) as ASPxTextBox;
                ASPxTextBox txt2 = ((ASPxTextBox)grid.FindEditFormTemplateControl("txtDiscount")) as ASPxTextBox;
                combo2.Value = vals[0];
                combo3.Value = vals[1];
                combo4.Value = vals[2];
                txt1.Text = vals[3].ToString();
                txt2.Text = vals[4].ToString();

            }
            
        }

        protected void grid_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {

        }

        protected void grid_HtmlFooterCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableFooterCellEventArgs e)
        {

        }

        protected void SqlOrder_Updating(object sender, SqlDataSourceCommandEventArgs e)
        {
            e.Command.Parameters["@Order_ID"].Value = Session["sOrder_ID"].ToString();
        }

        protected void ASPxButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Ordering.aspx");
        }

       

      
    }
}